<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="申请单号" prop="nos">
        <el-input v-model="queryParams.nos" placeholder="请输入申请单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="采购单号" prop="buyNos">
        <el-input v-model="queryParams.buyNos" placeholder="请输入采购单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="制单人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入制单人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="审计人" prop="auditBy">
        <el-input v-model="queryParams.auditBy" placeholder="请输入审计人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="人员姓名" prop="personName">
        <el-input v-model="queryParams.personName" placeholder="请输入人员姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="发票编号" prop="invoiceCode">
        <el-input v-model="queryParams.invoiceCode" placeholder="请输入发票编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="审核状态" prop="payStatus">
        <el-select clearable placeholder="请选择审核状态" v-model="queryParams.assessStatus">
          <el-option :key="dict.value" :label="dict.label" :value="dict.value"
            v-for="dict in dict.type.apply_assess_status" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间">
        <el-date-picker v-model="dateRange" style="display: flex;" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item label="是否上传发票" prop="isInvoice">
        <el-radio-group v-model="queryParams.isInvoice" @change="getList">>
          <el-radio v-for="dict in dict.type.yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="回款状态" prop="payStatus">
        <el-select clearable placeholder="请选择回款状态" v-model="queryParams.payStatus">
          <el-option :key="dict.value" :label="dict.label" :value="dict.value"
            v-for="dict in dict.type.apply_pay_status" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="danger" plain icon="el-icon-s-check" size="mini" @click="handleBatchBossAssess"
          v-hasPermi="['develop:PayApply:bossAssess']" :disabled="multiple">批量终审</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="queryParams.assessStatus === '0'">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddMerge"
          v-hasPermi="['develop:PayApply:add']">合并付款
        </el-button>
      </el-col>
      <el-col :span="1.5" v-if="queryParams.assessStatus === '0'">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddDeposit"
          v-hasPermi="['develop:PayApply:add']">申请定金
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddArrears"-->
      <!--                   v-hasPermi="['develop:PayApply:add']">申请尾款-->
      <!--        </el-button>-->
      <!--      </el-col>-->

    </el-row>
    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table" show-summary
       :summary-method="getSummaries" :max-height="tableMaxHeight" @sort-change="handleSortChange">
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column label="序号" type="index" align="center" width="50"></el-table-column>
      <el-table-column sortable label="申请单号 " align="center" prop="nos" width="120" :resizable="true"/>
      <el-table-column sortable label="制单人 " align="center" prop="createBy" width="120" :resizable="true"/>
      <el-table-column sortable label="审计人 " align="center" prop="auditBy" width="120" :resizable="true"/>
      <el-table-column label="采购单号 " align="center" prop="buyNos" width="120" show-overflow-tooltip :resizable="true"/>
      <el-table-column sortable align="center" label="采购类别" prop="ywType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.caigou_type" :value="scope.row.lvBuy.ywType"/>
        </template>
      </el-table-column>
      <el-table-column sortable label="申请时间" align="center" prop="applyTime" width="150" :resizable="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="供应商名称" align="center" prop="goodsSupplier.name" width="230" :resizable="true" />
      <el-table-column label="人员姓名" align="center" prop="personName" :resizable="true"/>
      <el-table-column align="center" label="付款类别" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_apply_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column sortable label="发票编号" align="center" prop="invoiceCode" show-overflow-tooltip :resizable="true" />
      <el-table-column label="申请付款金额" align="center" prop="totalMoney" :resizable="true"/>
      <el-table-column label="已付金额" align="center" prop="paidMoney" :resizable="true"/>
      <el-table-column label="剩余金额" align="center" prop="remainMoney" :resizable="true"/>
      <el-table-column align="center" label="审核状态" prop="assessStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.apply_assess_status" :value="scope.row.assessStatus" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="付款状态" prop="payStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.apply_pay_status" :value="scope.row.payStatus" />
        </template>
      </el-table-column>
      <el-table-column label="是否置顶" align="center" key="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isTop" active-value="0" inactive-value="1"
            @change="handleIsTopChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-document" v-if="scope.row.type !== '4'"
            @click="handleDetail(scope.row)" v-hasPermi="['develop:PayApply:edit']">详情
          </el-button>

          <el-popover placement="top" width="200">
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" icon="el-icon-money"
                v-if="isEmpty(scope.row.invoicePhoto) && scope.row.type !== '4'" @click="uploadInvoice(scope.row)"
                v-hasPermi="['develop:LvBuy:edit']">上传发票
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-finished"
                v-if="scope.row.assessStatus === '0' || scope.row.assessStatus === '3'" @click="handleAudit(scope.row)"
                v-hasPermi="['develop:PayApply:audit']">审计
              </el-button>

              <el-popconfirm :title="`确认同意撤销该付款单吗？`" @confirm="handleCancelApply(scope.row)"
                v-if="scope.row.assessStatus === '1'" style="margin: 0 10px;">
                <el-button slot="reference" size="mini" type="text" icon="el-icon-remove-outline"> 撤销申请
                </el-button>
              </el-popconfirm>

              <el-button size="mini" type="text" icon="el-icon-circle-check" v-if="scope.row.assessStatus === '2' || scope.row.assessStatus === '4'"
                @click="handleAssess(scope.row)" v-hasPermi="['develop:PayApply:bossAssess']">终审
              </el-button>

              <el-button size="mini" type="text" icon="el-icon-circle-check" v-if="scope.row.assessStatus === '4' && scope.row.payStatus === '0' "
                         @click="handleAssess(scope.row)" v-hasPermi="['develop:PayApply:bossAssess']">终审
              </el-button>

              <el-button size="mini" type="text" icon="el-icon-money"
                v-if="scope.row.assessStatus === '4' && scope.row.type !== '4' && scope.row.payStatus !== '2'"
                v-hasPermi="['develop:PayApply:applyPay']" @click="payRecordForm(scope.row)">打款
              </el-button>

              <el-button size="mini" type="text" icon="el-icon-money"
                v-if="scope.row.assessStatus === '4' && scope.row.type === '4' && scope.row.payStatus !== '2'"
                v-hasPermi="['develop:PayApply:applyPay']" @click="payRecordShippingForm(scope.row)">打款
              </el-button>


              <el-button size="mini" type="text" icon="el-icon-document" v-if="scope.row.assessStatus === '4'"
                @click="payRecordList(scope.row)" v-hasPermi="['develop:LvBuy:edit']">打款记录
              </el-button>

              <el-button size="mini" type="text" icon="el-icon-document" v-if="scope.row.type === '4'"
                @click="handleDetailForShipping(scope.row)" v-hasPermi="['develop:PayApply:edit']">详情
              </el-button>


              <el-button size="mini" type="text" icon="el-icon-printer" @click="handlePrint(scope.row)"
                v-hasPermi="['develop:PayApply:edit']">打印
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-time" @click="handleShowProcess(scope.row)">
                流转记录
              </el-button>
            </div>
            <el-button slot="reference" size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
          </el-popover>

        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <payApply-form ref="form" @ok="getList"></payApply-form>
    <pay-apply-merge-list-form ref="mergeListForm" @ok="getList"></pay-apply-merge-list-form>
    <lv-buy-list-module ref="buyListModule"></lv-buy-list-module>
    <lv-buy-list-deposit ref="buyListModuleDeposit"></lv-buy-list-deposit>
    <pay-record-form ref="payRecordForm" @ok="getList"></pay-record-form>
    <pay-record-shipping-form ref="payRecordShippingForm" @ok="getList"></pay-record-shipping-form>
    <pay-apply-detail ref="payApplyDetail"></pay-apply-detail>
    <pay-apply-shipping-detail ref="payApplyShippingDetail"></pay-apply-shipping-detail>
    <pay-record-list-module ref="payRecordList"></pay-record-list-module>
    <pay-apply-audit-form ref="payAuditForm" @ok="getList"></pay-apply-audit-form>
    <pay-apply-assess-form ref="payAssessForm" @ok="getList"></pay-apply-assess-form>
    <pay-apply-assess-form-batch ref="payAssessFormBatch" @ok="getList"></pay-apply-assess-form-batch>
    <invoice-upload-form ref="invoiceUploadForm" @ok="getList"></invoice-upload-form>
    <pay-apply-detail-print ref="payApplyDetailPrint"></pay-apply-detail-print>
    <el-drawer title="流转记录" :visible.sync="processDrawerShow" :with-header="true" size="20%">
      <process-pay-apply-timeline :payApplyId="payApplyId"></process-pay-apply-timeline>
    </el-drawer>

  </div>
</template>

<script>
import { accAdd, deleteAction, downloadFile, getAction, isEmpty, updateAction } from '@/api/manage'
import PayApplyForm from '@/views/develop/payApply/module/PayApplyForm'
import PayApplyMergeListForm from "@/views/develop/payApply/module/PayApplyMergeListForm.vue";
import LvBuyListModule from "@/views/develop/lvBuy/module/LvBuyListModule.vue";
import LvBuyListHardware from "@/views/develop/lvBuy/module/LvBuyListDeposit.vue";
import PayRecordForm from "@/views/develop/payRecord/module/PayRecordForm.vue";
import PayApplyDetail from "@/views/develop/payApply/module/PayApplyDetail.vue";
import PayRecordListModule from "@/views/develop/payRecord/module/PayRecordListModule.vue";
import PayApplyAssessForm from "@/views/develop/payApply/module/PayApplyAssessForm.vue";
import PayApplyAuditForm from "@/views/develop/payApply/module/PayApplyAuditForm.vue";
import LvBuyListDeposit from "@/views/develop/lvBuy/module/LvBuyListDeposit.vue";
import InvoiceUploadForm from '@/views/develop/payApply/module/InvoiceUploadForm.vue';
import PayApplyDetailPrint from "@/views/develop/payApply/module/PayApplyDetailPrint.vue";
import PayApplyAssessFormBatch from "@/views/develop/payApply/module/PayApplyAssessFormBatch.vue";
import PayApplyShippingDetail from "@/views/develop/payApply/module/PayApplyShippingDetail.vue";
import PayRecordShippingForm from "@/views/develop/payRecord/module/PayRecordShippingForm.vue";
import { parseTime } from "../../../utils/ruoyi";
import ProcessPleaseBuyTimeline from "@/views/develop/process/processPleaseBuy/ProcessPleaseBuyTimeline.vue";
import ProcessPayApplyTimeline from "@/views/develop/process/processPayApply/ProcessPayApplyTimeline.vue";

export default {
  name: "PayApplyList",
  dicts: ["pay_apply_type", "apply_pay_status", "apply_assess_status", "yes_no","caigou_type"],
  components: {
    ProcessPayApplyTimeline,
    ProcessPleaseBuyTimeline,
    PayRecordShippingForm,
    PayApplyShippingDetail,
    PayApplyAssessFormBatch,
    PayApplyDetailPrint,
    LvBuyListDeposit,
    PayApplyAuditForm,
    PayApplyAssessForm,
    PayRecordListModule,
    PayApplyDetail,
    PayRecordForm,
    LvBuyListModule,
    LvBuyListHardware,
    PayApplyMergeListForm,
    PayApplyForm,
    InvoiceUploadForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 付款申请单表格数据
      dataList: [],
      selections: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        isInvoice: null,
        buyId: null,
        invoiceCode: null,
        assessStatus: null,
        createBy: null,
        auditBy: null,
        params: {},
        orderByColumn: "isTop asc,nos",
        isAsc: "desc"
      },
      url: {
        list: '/payApply/payApply/list',
        remove: '/payApply/payApply/',
        cancel: '/payApply/payApply/cancel/',
        edit: '/payApply/payApply/edit',
      },
      tableMaxHeight: window.innerHeight - 320,
      payApplyId: null,
      processDrawerShow: false,
    };
  },
  created() {
    let that = this;
    that.queryParams.assessStatus = that.$route.query.assessStatus;
    that.queryParams.isInvoice = that.$route.query.isInvoice;
    this.getList();
    window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.getTableHeight)
  },
  methods: {
    parseTime,
    isEmpty,
    uploadInvoice(row) {
      this.$refs.invoiceUploadForm.handleUpdate(row);
    },
    /** 排序触发事件 */
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.handleQuery();
    },    /** 查询付款申请单列表 */
    getList() {
      this.loading = true;
      this.addDateRange(this.queryParams, this.dateRange, "ApplyTime");
      getAction(this.url.list, this.queryParams).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selections = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAddMaterial() {
      this.$refs.buyListModule.show();
    },


    /** 新增按钮操作 */
    handleAddArrears() {
      this.$refs.buyListModuleDeposit.show("Y", "3");
    },

    handleAddDeposit() {
      this.$refs.buyListModuleDeposit.show("Y", "0");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    handleAddMerge() {
      this.$refs.mergeListForm.show();
    },

    payRecordForm(row) {
      this.$refs.payRecordForm.handleAddByApply(row);
    },

    /** 运费打款 */
    payRecordShippingForm(row) {
      this.$refs.payRecordShippingForm.handleAddByApply(row);
    },


    handleDetail(row) {
      this.$refs.payApplyDetail.showDetail(row.id, row.buyId);
    },

    /** 运费详情 */
    handleDetailForShipping(row) {
      this.$refs.payApplyShippingDetail.showDetail(row.id, row.buyId);
    },

    payRecordList(row) {
      let applyId = row.id;
      this.$refs.payRecordList.showPayRecordList(applyId);
    },

    handleCancelApply(row) {
      getAction(this.url.cancel + row.id, {}).then(response => {
        this.getList();
      }).catch(() => {
      });
    },

    handleAudit(row) {
      this.$refs.payAuditForm.handleUpdate(row);
    },
    handleAssess(row) {
      this.$refs.payAssessForm.handleUpdate(row);
    },

    handleBatchBossAssess() {
      const ids = this.ids;
      this.$refs.payAssessFormBatch.handleBatchAssess(ids);
    },

    handlePrint(row) {
      this.$refs.payApplyDetailPrint.showDetail(row.id, row.buyId);
    },

    // 是否置顶修改
    handleIsTopChange(row) {
      let that = this;
      let text = row.isTop === "0" ? "置顶" : "取消置顶";
      this.$modal.confirm('确认要"' + text + '""' + row.nos + '"付款申请单吗？').then(function () {
        let params = { "id": row.id, "isTop": row.isTop };
        updateAction(that.url.edit, params).then(response => {
          that.getList();
        }).catch(() => {
        });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.isTop = row.isTop === "0" ? "1" : "0";
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      let that = this;
      that.loading = false;
      that.$confirm('是否确认导出付款明细?', "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        downloadFile('/payApply/payApply/export', that.queryParams);
      });
    },

    /** 查看流转信息 */
    handleShowProcess(row) {
      this.processDrawerShow = true;
      this.payApplyId = row.id;
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if (column.property === "totalMoney" || column.property === "paidMoney" || column.property === "remainMoney") {
          sums[index] = values.reduce((prev, curr) => {

            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev, curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },







  }
};
</script>
